package com.my.swas.sso.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.my.swas.common.jwt.JWTUtils;
import com.my.swas.common.utils.DateUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.ObjectUtils;

/**
 * @Description:
 * @author: :MaYong
 */
//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("com.my.swas.sso.module.*.mapper.*")
public class MybatisPlusConfig implements MetaObjectHandler {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }

    /**
     * 乐观锁mybatis插件
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        String userAccount = JWTUtils.getUserAccount();
        this.setFieldValByName("createdTime", DateUtils.today(),metaObject);
        this.setFieldValByName("lastModifyTime", DateUtils.today(),metaObject);
        if(!ObjectUtils.isEmpty(userAccount)) {
            this.setFieldValByName("creator", userAccount, metaObject);
            this.setFieldValByName("lastModifier", userAccount, metaObject);

            this.setFieldValByName("creatorId", JWTUtils.getUserId(), metaObject);
            this.setFieldValByName("lastModifierId", JWTUtils.getUserId(), metaObject);

        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userAccount = JWTUtils.getUserAccount();
        this.setFieldValByName("lastModifyTime", DateUtils.today(),metaObject);
        if(!ObjectUtils.isEmpty(userAccount)) {
            this.setFieldValByName("lastModifier", userAccount, metaObject);
            this.setFieldValByName("lastModifierId", JWTUtils.getUserId(), metaObject);

        }
    }
}

